package com.thrc.borrow.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInspectInterceptor extends HandlerInterceptorAdapter {

	public static Logger logger = Logger
			.getLogger(LoginInspectInterceptor.class);
	private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>(
			"StopWatch-StartTime");

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

		long endTime = System.currentTimeMillis(); // 2、结束时间
		long beginTime = startTimeThreadLocal.get();// 得到线程绑定的局部变量（开始时间）
		long consumeTime = endTime - beginTime; // 3、消耗的时间
		logger.info("request url ******* " + request.getServletPath()
				+ "\tCost time " + consumeTime);

	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		long beginTime = System.currentTimeMillis();// 1、开始时间
		startTimeThreadLocal.set(beginTime);// 线程绑定变量（该数据只有当前请求的线程可见）

		String servletPath = request.getServletPath();
		// 1、请求到登录页面 放行
		if (servletPath.startsWith("/system/tologin")
				|| servletPath.startsWith("/system/checkLogin")
				|| servletPath.startsWith("/user/login")) {
			return true;
		}

		// 3、如果用户已经登录 放行
		if (request.getSession().getAttribute("user") != null) {
			// 更好的实现方式的使用cookie
			return true;
		}

		// 4、非法请求 即这些请求需要登录后才能访问
		// 重定向到登录页面
		response.sendRedirect(request.getContextPath() + "/system/tologin");
		return false;
	}
}
